<template lang="pug">
  view
    view.topTabBar(:style="{position:headerPosition,top:headerTop}")
      view.grid(v-for="(grid,tbIndex) in orderType"  :key="tbIndex"  @tap="showType(tbIndex)")
        view.text(:class="[tbIndex === tabbarIndex?'on':'']") {{grid}}
    view.order-list
      view.list
        view.onorder(v-if="orderList.length==0")
          image(src="http://120.55.49.138/ShopMall/static/img/noorder.png")
          view.text            没有相关订单
        view.row(v-for="(row,index) in orderList"  :key="index")
          view.type 订单号【{{row.id}}】**下单时间【{{row.createTime}}】**
          view.row(v-for="(row1,index1) in row.orderItemList"  :key="index1")
            view.order-info
              view.left
                image(:src="row1.productPic + $pictureResolution(0, 375)" webp)
              view.right
                view.name                商品名称:{{row1.productName}}
                view.spec 规格:{{row1.sp1}} {{!!row1.sp4 ? '属性:' + row1.sp4 : ''}}
                view.price-number                ￥
                  view.price {{row1.productPrice}} 								x
                  view.number {{row1.productQuantity}}
            view(style="font-size:26upx;margin-top:10upx") 店铺: {{row1.shop_name}}
          view.detail
            view.sum 合计￥
              view.price {{row.totalAmount}}
            view.nominal (含运费 ￥{{row.freightAmount}})
          view.btns
            block(v-if="row.status==0")
              view.default(@tap="cancelOrder(row)") 取消订单
              view.pay(@tap="toPayment(row)") 付款
            block(v-if="row.status==1")
              view.default(@tap="remindDeliver(row)") 提醒发货
              view.pay(@tap="returnApplyOrder(row)") 我要退款
            block(v-if="row.status==2")
              view.default(@tap="showLogistics(row)") 查看物流
              view.pay(@tap="toRefirm(row)") 确认收货
              view.pay(@tap="returnApplyOrder(row)") 我要退货
            block(v-if="row.status==3")
              view.default(@tap="toRefly(row)") 评价
              view.default(@tap="toRefly(row)") 再次购买
            block(v-if="row.status==4")
              view.default(@tap="toRefly(row)") 再次购买
            block(v-if="row.status==5")
              view.default 已取消
            block(v-if="row.status>=6")
              view.default(@tap="view(row)") 查看进度
</template>
<script>
import * as _ from "underscore";
import {mapActions, mapGetters, mapMutations, mapState} from "vuex";
import {OrderApi} from "@/api/user";

const CREATE_RETURN_ORDER = function ({orderId, orderSn, productName, productPic, productPrice}) {
  return {
    "description": "",
    "memberUsername": "",
    "orderId": orderId,
    "orderSn": orderSn,
    "productAttr": "",
    "productBrand": "",
    "productCount": 0,
    "productId": 0,
    "productName": productName,
    "productPic": productPic,
    "productPrice": productPrice,
    "productRealPrice": 0,
    "proofPics": "",
    "reason": "",
    "returnName": "",
    "returnPhone": ""
  }
}

export default {
  data() {
    return {
      headerPosition: "fixed",
      headerTop: "0px",
      returnAddr: "",
    };
  },
  computed: {
    ...mapState("orderListPage", ['orderType', 'tabbarIndex']),
    ...mapState("orderListPage/list", ['finish']),
    ...mapGetters("orderListPage", ['orderList'])
  },
  async onLoad(option) {
    let tbIndex = parseInt(option.tbIndex)
    this.setTableBarIndex(tbIndex)
    await this.getPageData(1);
  },
  methods: {
    ...mapActions("orderListPage", ['fetchList', 'fetchNextData']),
    ...mapMutations("orderListPage", {
      "setTableBarIndex": "SET_TABLE_TAR_INDEX"
    }),
    async getPageData(p = 1) {
      uni.showLoading({title: "加载中"});
      await this.fetchList(p)
      setTimeout(() => {
        uni.hideLoading();
      }, 500)
    },
    async showType(tbIndex) {
      if (this.tabbarIndex === tbIndex) return;
      this.setTableBarIndex(tbIndex);
      await this.getPageData(1);
    },
    showLogistics(row) {
      uni.navigateTo({
        url: 'logistics?tbIndex=' + row.id
      });
    },
    remindDeliver(row) {
      uni.showToast({
        title: '已提醒商家发货'
      })
    },
    view(row) {
      let titi = '';
      if (row.status == 6) titi = '->申请退款';
      if (row.status == 7) titi = '->正在退款';
      if (row.status == 8) titi = '->退款成功 订单关闭';
      if (row.status == 9) titi = '->退款失败，请人工处理';
      if (row.status == 10) titi = '->申请退款';
      if (row.status == 11) {
        titi = '->退货申请接受';
        this.returnAddr = '';
        this.$Request.post(this.$api.returnApply.getDetail + '?order_id=' + row.id, {}, this.hearder + ' ' + this.sessionid).then(res => {
          if (res.code == 200) {
            this.returnAddr = '地址：' + res.data.companyAddress.province +
                res.data.companyAddress.city +
                res.data.companyAddress.region +
                res.data.companyAddress.detailAddress + '\n' +
                '收件人：' + res.data.companyAddress.name + '\n' +
                '电话：' + res.data.companyAddress.phone;
            uni.showModal({
              title: '退货信息',
              content: titi + '\n' + this.returnAddr,
              success: (res) => {
                if (res.confirm) {
                  console.log('用户点击确定');
                } else if (res.cancel) {
                  console.log('用户点击取消');
                }
              }
            });
          }
        });
      }
      if (row.status == 12) titi = '->退货收到，正在退款';
      if (row.status == 13) titi = '->退货退款成功，订单关闭';
      if (row.status == 14) titi = '->退货退款失败，人工处理';
      if (row.status != 11) {
        uni.showModal({
          title: '退货进度',
          content: titi,
          success: (res) => {
            if (res.confirm) {
              console.log('用户点击确定');
            } else if (res.cancel) {
              console.log('用户点击取消');
            }
          }
        });
      }
    },
    cancelOrder(row) {
      uni.showModal({
        title: '取消订单',
        content: '确定取消此订单？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({title: "加载中..."});
            await OrderApi.cancelOrder({
              orderId: row.id
            })
            await this.fetchList(1);
            uni.hideLoading();
            uni.showToast({title: "取消成功"})
          }
        }
      });
    },
    returnApplyOrder(row) {
      uni.showModal({
        title: '订单退货',
        content: '确定订单退货？',
        success: async (res) => {
          if (res.confirm) {
            const {id, orderSn, orderName, productPic, totalAmount} = row;

            uni.showLoading({title: "加载中..."});
            await OrderApi.returnApplyCreate(CREATE_RETURN_ORDER({
              orderId: id, orderSn, productName: orderName, productPic, productPrice: totalAmount
            }))
            await this.fetchList(1);
            uni.hideLoading();
            uni.showToast({title: "退款成功"})
          }
        }
      });
    },
    toRefirm(row) {
      uni.showModal({
        title: '订单收货',
        content: '确定订单收货？',
        success: async (res) => {
          if (res.confirm) {
            uni.showLoading({title: "加载中..."});
            await OrderApi.refirm({
              id: row.id
            })
            await this.fetchList(1);
            uni.hideLoading();
            uni.showToast({title: "收货确认成功"})
          }
        }
      });
    },
    toPayment(row) {
      uni.setStorage({
        key: 'paymentOrder',
        data: [row],
        success: () => {
          uni.hideLoading();
          uni.navigateTo({
            url: '../../pay/payment/payment?amount=' + row.totalAmount + '&orderid=' + row.id + '&name=' + _.get(row, ['orderItemList', 0, 'productName'])
          })
        }
      })
    },
    toRefly(row) {
      const {shopId, productId} = _.get(row, ['orderItemList', 0])
      uni.navigateTo({
        url: '../../goods/goods?cid=' + productId + "&shopId=" + shopId
      });
    }
  },
  onReachBottom() {
    if (!this.finish) {
      this.fetchNextData();
    }
  },
}
</script>

<style lang="scss">
@import "orderList.scss";
</style>
